#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Seed 表模型定义
script name: seed
Created on 2020/2/15 18:00 by PyCharm
@author: fujianjian
"""
from datetime import datetime, date

from app import db


class Seed(db.Model):
    __tablename__ = 't_seeds'
    id = db.Column(db.Integer, primary_key=True, comment='主键')
    name = db.Column(db.String(127), comment='种子名称', index=True, nullable=False)
    hot = db.Column(db.Integer, comment='热度')
    size = db.Column(db.String(32), comment='大小')
    uri = db.Column(db.String(64), comment='链接')
    made_time = db.Column(db.TIMESTAMP, comment='制作时间')
    search_channel = db.Column(db.String(32), comment='查找渠道')
    created_time = db.Column(db.TIMESTAMP, default=datetime.utcnow(), comment='创建时间')
    updated_time = db.Column(db.TIMESTAMP, default=datetime.utcnow(), comment='更新时间')
    product_id = db.Column(db.Integer, db.ForeignKey('t_productions.id'))

    def keys(self):
        return ['id', 'name', 'hot', 'size', 'uri',
                'made_time', 'search_channel', 'created_time',
                'updated_time', 'product_id']

    def __getitem__(self, item):
        attr = getattr(self, item)
        if isinstance(attr, datetime):
            attr.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(attr, date):
            attr.strftime('%Y-%m-%d')
        return attr


class Production(db.Model):
    __tablename__ = 't_productions'
    id = db.Column(db.Integer, primary_key=True, comment='组件')
    name = db.Column(db.String(127), comment='作品名称', index=True, nullable=False)
    pub_time = db.Column(db.TIMESTAMP, comment='发布时间')
    category = db.Column(db.String(64), comment='类别')
    type = db.Column(db.String(32), comment='类型')
    intro = db.Column(db.String(255), comment='简介')
    cover_uri = db.Column(db.String(64), comment='封面uri')
    has_search = db.Column(db.Boolean, comment='是否查找过')
    seed_count = db.Column(db.Integer, default=0, comment='种子数量')
    created_time = db.Column(db.TIMESTAMP, default=datetime.utcnow(), comment='创建时间')
    updated_time = db.Column(db.TIMESTAMP, default=datetime.utcnow(), comment='更新时间')

    seed_list = db.relationship('Seed', backref='production')

    def keys(self):
        return ['id', 'name', 'pub_time', 'category', 'type',
                'intro', 'cover_uri', 'has_search', 'seed_count',
                'created_time', 'updated_time']

    def __getitem__(self, item):
        attr = getattr(self, item)
        if isinstance(attr, datetime):
            attr = attr.strftime('%Y-%m-%d %H:%M:%S')
        return attr
